import AITalk from './talkTemplate';
import Logger from './Logger';
import { Message } from 'element-ui';
import { downloadNluKeys, getAllWorkstepName, getNodeTitle } from './utils';
import { getNextStep } from './changeNextStep';
import { replaceNodeId, verifyAllCompletion, getAllParentNodes, getTitle } from '@/views/bpmn/utility/utility';
import _ from 'lodash';
import { initModalDataWithType, parseModalDataWithType } from './workstep/index';

const log = new Logger(1, 'AI-TEMPLATE');

const NodeEnum = {
	HANG_UP: 'hangup',
	SEND_MESSAGE: 'send-message',
	FACE_COMPARE: 'compareFace',
	DETECT_LIVING_FACE: 'detectLivingFace',
	VARIABLE_COLLECTION: 'variableCollection'
};

class WorkFlow {
	constructor() {
		this.version = -1;
		this.name = null;
		this.talks = {};
		this.bpmnXml = null;
		this.callStart = null;
		this.robotProperty = {
			videoType: '',
			audioType: '',
			silentVideo: '',
			talkingVideo: ''
		};
		this.previousRobotProperty = {
			videoType: '',
			audioType: '',
			silentVideo: '',
			talkingVideo: ''
		};
		this.videoMarks = { isOn: false }; // 是否开启打点
		this.exceptionNext = 'hangup'; // 机器人异常处理
		this.serviceException = AITalk.hangup; // 机器人异常处理
		this.compareFace = null; // 全局人脸比对数据
		this.detectLivingFace = null; // 全局活体检测数据
		this.isDetail = false; // 是否显示详情
		this.businessId = null; // 业务场景ID
		this.templateId = null; // ai工作流ID
		this.configTabs = 'ai-property';
		this.silentVideoSource = null;
		this.talkingVideoSource = null;
		this.nextStepOption = []; // 下一步选项
		this.startNode = null;
		this.changedNextSteps = []; // 模板变更下一步缓存数据
		this.breakRuleNodes = []; // 扫码失败/扫码超时的流程分支中查阅等待节点
		this.ivvrOptionsVideo = [];
		this.cloneForm = null;
		this.isOldVersion = false;
		this.messageSummarySource = []; // 信息汇总节点
	}

	// 打开新模版，设置默认值
	setDefault() {
		this.version = -1;
		this.name = null;
		this.talks = {};
		this.bpmnXml = null;
		this.callStart = null;
		this.robotProperty = {
			videoType: '',
			audioType: '',
			silentVideo: '',
			talkingVideo: ''
		};
		this.previousRobotProperty = {
			videoType: '',
			audioType: '',
			silentVideo: '',
			talkingVideo: ''
		};
		this.videoMarks = { isOn: false }; // 是否开启打点
		this.exceptionNext = 'hangup'; // 机器人异常处理
		this.serviceException = AITalk.hangup; // 机器人异常处理
		this.compareFace = null; // 全局人脸比对数据
		this.detectLivingFace = null; // 全局活体检测数据
		this.isDetail = false; // 是否显示详情
		this.businessId = null; // 业务场景ID
		this.templateId = null; // ai工作流ID
		this.configTabs = 'ai-property';
		this.silentVideoSource = null;
		this.talkingVideoSource = null;
		this.nextStepOption = []; // 下一步选项
		this.startNode = null;
		this.changedNextSteps = []; // 模板变更下一步缓存数据
		this.breakRuleNodes = []; // 扫码失败/扫码超时的流程分支中查阅等待节点
		this.ivvrOptionsVideo = [];
		this.cloneForm = null;
	}

	getTalkId(talkId) {
		if (!talkId) {
			log.error('getTalkId error:', 'talkId is null');
			return;
		}
		const id = talkId.split('_')[0];
		return id;
	}

	/** 生成机器人话术异常处理话术 */
	generateRobotException(exceptionNext) {
		if (exceptionNext === NodeEnum.HANG_UP) {
			return AITalk.hangup;
		} else if (exceptionNext === NodeEnum.SEND_MESSAGE) {
			return AITalk.transfer;
		}
	}
	/** 生成全局活体检测和人脸比对参数 */
	generateFaceLivingAndCompare(type) {
		if (!type) {
			return null;
		}
		return NodeEnum.DETECT_LIVING_FACE;
	}

	/** 机器人下拉选择选项 */
	getRebotExceptionOptions() {
		return AITalk.rebotExceptionOptions;
	}

	/** 获取 Label 数据 */
	getKeyLabelOptions() {
		return AITalk.keyLabelOptions;
	}

	/** 设置视频打点 */
	setVideoMarks(videoMarks = { isOn: false }) {
		this.videoMarks = videoMarks;
	}

	/** 获取视频打点配置 */
	getVideoMarks() {
		return this.videoMarks.isOn;
	}

	/** 设置工作流名称 */
	setWorkFlowName(name) {
		this.name = name;
	}
	/** 设置是否含有旧版本数据 */
	setOldVersion(status) {
		this.isOldVersion = status;
	}

	/** 设置工作流版本 */
	setWorkFlowVersion(version) {
		this.version = version;
	}

	/** 设置缓存的前一个选中的全局 AI 坐席属性配置 */
	setPreviousRobotProperty(previousRobotProperty) {
		this.previousRobotProperty = { ...this.previousRobotProperty, ...previousRobotProperty };
		log.debug('setPreviousRobotProperty:', this.previousRobotProperty);
	}
	/** 获取缓存的前一个选中的全局 AI 属性配置 */
	getPreviousRobotProperty() {
		return this.previousRobotProperty;
	}
	/** 设置全局 AI 坐席属性配置 */
	setRobotProperty(robotProperty) {
		this.robotProperty = { ...this.robotProperty, ...robotProperty };
		log.debug('setRobotProperty:', this.robotProperty);
	}

	/** 获取全局 AI 属性配置 */
	getRobotProperty() {
		return this.robotProperty;
	}

	/** 设置激活tab */
	setConfigTab(tab) {
		this.configTabs = tab;
		log.debug('激活tabs:', this.configTabs);
	}

	/** 设置是否显示详情 */
	setIsDetail(status) {
		this.isDetail = status;
		log.info('预览模式:', this.isDetail);
	}
	/** 设置业务场景ID */
	setBusinessId(businessId) {
		this.businessId = businessId;
		log.info('设置业务场景ID:', this.businessId);
	}

	/** 获取业务场景ID */
	getBusinessId() {
		return this.businessId;
	}
	/** 设置ai工作流ID */
	setTemplateId(templateId) {
		this.templateId = templateId;
		log.info('设置ai工作流ID:', this.templateId);
	}

	/** 获取ai工作流ID */
	getTemplateId() {
		return this.templateId;
	}

	/** 设置机器人异常处理模式 */
	setExceptionNext(mode = 'hangup') {
		console.log(this.global);
		this.exceptionNext = mode;
		this.serviceException = this.generateRobotException(mode);
		log.info('机器人异常处理方式:', mode, this.serviceException);
	}
	/** 设置活体检测数据 */
	setDetectLivingFace(params) {
		if (!this.detectLivingFace) {
			this.detectLivingFace = { ...AITalk.faceLivingAndCompare };
		}
		this.detectLivingFace = { ...this.detectLivingFace, ...params };
		log.debug('设置全局活体检测参数:', this.detectLivingFace);
	}

	/** 设置全局人脸比对数据 */
	setCompareFace(params) {
		if (!this.compareFace) {
			this.compareFace = { ...AITalk.faceLivingAndCompare };
		}

		this.compareFace = { ...this.compareFace, ...params };
		log.debug('设置人脸比对参数:', this.compareFace);
	}

	/** 设置开始节点 */
	setStartNode(node) {
		this.startNode = node;
	}

	/** 设置AI工作流 */
	setTalks(talks) {
		this.talks = talks;
		this.updateNextStepOption();
	}

	/** 新增 AI 工作流节点 */
	addTalk(talk) {
		let data = _.cloneDeep(this.talks);
		let talkName = this.getTalkId(talk.id);
		let parentNode = getAllParentNodes(this.talks, talk.id);
		talk.hasStartNode = parentNode.includes(this.startNode);
		data[talk.no] = { ...AITalk.getTalks(talkName), ...talk };
		this.talks = _.cloneDeep(data);
		this.updateNextStepOption();
		log.debug('节点信息：', JSON.stringify(data[talk.no]));
	}

	/** 删除单个节点 */
	removeTalk(talkID) {
		const step = this.talks[talkID];
		if (step) {
			delete this.talks[talkID];
		}
		this.updateNextStepOption();
		// log.debug('removeTalk:', talkID);
	}

	/** 替换节点 */
	replaceNodeId(node) {
		let data = _.cloneDeep(this.talks);
		let step = data[node.parentId];
		if (step) {
			replaceNodeId(step.scanCode || step.requestLocation || step, node);
			this.talks = _.cloneDeep(data);
		}
	}

	/** 是否配置过全局属性 */
	hasRobotProperty() {
		if (this.robotProperty.videoType) {
			return true;
		}
		return false;
	}

	/** 提示配置全局属性 */
	notifyConfRobotProperty() {
		if (!this.hasRobotProperty()) {
			Message.warning('请先在全局配置处完善AI坐席属性！');
			return true;
		}
		return false;
	}

	/** 设置模板静默视频资源 */
	setSilentVideoSource(source) {
		this.silentVideoSource = { ...source };
		log.debug('选择的静默视频资源：', this.silentVideoSource);
	}

	/** 设置模板播报视频资源 */
	setTalkingVideoSource(source) {
		this.talkingVideoSource = { ...source };
		log.debug('选择的播报视频资源：', this.talkingVideoSource);
	}

	/** 获取模板静默视频资源 */
	getSilentVideoSource() {
		return this.silentVideoSource;
	}
	/** 获取模板播报视频资源 */
	getTalkingVideoSource() {
		return this.talkingVideoSource;
	}

	/** 设置下一步选项 */
	setNextStepOption(nextStepOption) {
		this.nextStepOption = nextStepOption;
		// log.debug('nextStepOption:', this.nextStepOption);
	}

	/** 更新下一步选项 */
	updateNextStepOption() {
		let nextSteps = getAllWorkstepName(this.talks);
		this.setNextStepOption(nextSteps);
	}

	getChangeNextStep(talkId, node) {
		if (!node) {
			log.error('getChangeNextStep:', 'node is null');
		}

		const id = this.getTalkId(talkId);
		const previousTalk = this.talks[id];
		const nextSteps = getNextStep(id, previousTalk, node);
		return nextSteps;
	}

	/** 设置模板变更缓存数据 */
	setChangedNextSteps(steps) {
		if (!steps) {
			log.error('setChangedNextSteps:', 'steps is null');
			return;
		}

		if (!steps.steps) {
			log.error('setChangedNextSteps:', 'steps is null');
			return;
		}

		_.forEach(steps, item => {
			if (item.previous) {
				this.hasBreakRuleNodes();
				if (AITalk.IgnoreChangeNextStepNode.indexOf(item.previous) && item.current) {
					let data = _.cloneDeep(this.talks);
					console.log('verifyAllCompletion');
					verifyAllCompletion(data, '', 'VERIFY_MESSAGE_SUMMARY');
					this.talks = { ...data };
				}
			}
		});

		this.changedNextSteps = { ...steps };
	}

	/** 是否命中空白节点 */
	hasBreakRuleNodes(node) {
		_.forEach(this.breakRuleNodes, breakRuleNodes => {
			const nodesString = breakRuleNodes.join(',');
			if (nodesString.indexOf(node.previous) !== -1) {
				breakRuleNodes.map(nodeId => this.filterWaitingReadNode(nodeId));
			}
		});
	}

	/** 节点是否是查阅等待 */
	hasWaitingReadNode(nodeId) {
		return nodeId.indexOf('waitingRead') !== -1;
	}

	/** 筛选查阅等待节点 */
	filterWaitingReadNode(nodes) {
		for (let i = 0; i < nodes.length; i++) {
			if (this.hasWaitingReadNode) {
				let data = _.cloneDeep(this.talks);
				const step = data[nodes[i]];
				if (step) {
					step.breakRule = false;
					this.talks = { ...data };
				}
			}
		}
	}

	/** 获取下一步选项 */
	getNextStepOption() {
		return this.nextStepOption;
	}

	/** 获取单个节点数据 */
	getTemplateNodeTalk(node) {
		let talk = this.talks[node];
		if (talk) {
			return talk;
		}
		log.error('未找到节点信息：', node);
	}

	/** 生成节点属性 */
	getTemplateTalkProperty() {
		const talk = _.cloneDeep(AITalk.generateTalk());
		AIWorkflow.cloneForm = talk;
		return talk;
	}

	/** 设置模板标题 */
	setTemplateTitle(taskId) {
		return getNodeTitle(taskId);
	}

	// input框只能输入整数，获取键盘码
	prevent(e) {
		if (!e) {
			log.error('event is undefined');
			return;
		}
		let keynum = window.event ? e.keyCode : e.which;
		if (keynum === 189 || keynum === 190 || keynum === 109 || keynum === 110) {
			Message.warning('禁止输入小数以及负数');
			e.target.value = '';
		}
	}

	// 设置信息汇总项
	setMessageSummarySource(taskId) {
		const parentNotes = getAllParentNodes(this.talks, taskId);
		const sures = [];
		let nodes = Array.from(new Set(parentNotes));
		nodes.map(item => {
			if (AITalk.messageSummaryNode.indexOf(this.getTalkId(item)) > -1 && this.talks[item].hasStartNode) {
				const option = { node: item, name: getTitle(item) };
				sures.push(option);
			}
		});
		return sures;
	}

	validateMessageSummary(sures, taskId) {
		const summary = [];
		if (this.talks[taskId].summary && this.talks[taskId].summary.length > 0) {
			this.talks[taskId].summary.forEach(v => {
				if (sures.find(k => k.node === v.node)) {
					summary.push(v);
				}
			});
		}
		return summary;
	}

	validateStartNode() {}

	/**
	 * 校验input框，输入时间间隔
	 * @param {input} e
	 * @param {number} min 最小值
	 * @param {number} max 最大值
	 */
	preventInputIntervalMs(e, min, max) {
		if (!e) {
			log.error('event is undefined');
			return;
		}
		let keynum = window.event ? e.keyCode : e.which;
		if (keynum === 189 || keynum === 190 || keynum === 109 || keynum === 110) {
			Message.warning('禁止输入小数以及负数');
			e.target.value = '';
		}
		if (e.target && e.target.value < min) {
			Message.warning(`时间间隔最小${min}ms`);
		}
		if (e.target && e.target.value > max) {
			Message.warning(`时间间隔最大${max}ms`);
		}
	}

	/**
	 * 校验input框，人脸对比&活体检测阈值
	 * @param {input} e
	 * @param {number} min 最小值
	 * @param {number} max 最大值
	 */
	preventInputConfidence(e, min, max) {
		if (!e) {
			log.error('event is undefined');
			return;
		}
		let keynum = window.event ? e.keyCode : e.which;
		if (keynum === 189 || keynum === 190 || keynum === 109 || keynum === 110) {
			Message.warning('禁止输入小数以及负数');
			e.target.value = '';
		}
		if (e.target && e.target.value < min) {
			Message.warning(`阈值最小${min}ms`);
		}
		if (e.target && e.target.value > max) {
			Message.warning(`阈值最大${max}ms`);
		}
	}

	/** 下载 NLP 语料库 */
	downloadNluKeys(libType, point) {
		return downloadNluKeys(libType, point);
	}

	/** 模板属性校验规则 */
	getTemplateValidateRules(talkId) {
		const id = this.getTalkId(talkId);
		return AITalk.templateValidateRules(id, this.getRobotProperty(), this.cloneForm);
	}

	/** 获取节点数据 */
	getTemplateNode(talkId) {
		const id = this.getTalkId(talkId);
		return AITalk.getTalks(id);
	}

	/** 验证全局人脸检测参数 */
	validateFaceCompare() {
		const { intervalMS = null, confidence = null, isRealTime = false } = this.compareFace;
		if (!isRealTime) {
			console.log('未开启人脸检测');
			return 1;
		}
		if (!intervalMS) {
			Message.info('请设置人脸检测间隔');
			return 0;
		}
		if (!confidence) {
			Message.info('请设置人脸检测相似度');
			return 0;
		}
		if (intervalMS <= 0) {
			Message.info('请设置正确的人脸检测间隔');
			return 0;
		}
		if (confidence <= 0 || confidence > 100) {
			Message.info('请设置正确的人脸检测相似度(1-100)');
			return 0;
		}
		if (intervalMS < 1000) {
			Message.info('请设置人脸対比检测间隔最少1000');
			return 0;
		}
		return 1;
	}

	/** 验证全局活体检测参数 */
	validateDetectLivingFace() {
		const { intervalMS = null, confidence = null, isRealTime = false } = this.detectLivingFace;
		if (!isRealTime) {
			console.log('未开启活体检测');
			return 1;
		}
		if (!intervalMS) {
			Message.info('请设置活体检测间隔');
			return 0;
		}
		if (!confidence) {
			Message.info('请设置活体检测相似度');
			return 0;
		}
		if (intervalMS <= 0) {
			Message.info('请设置正确的活体检测间隔');
			return 0;
		}
		if (confidence <= 0 || confidence > 100) {
			Message.info('请设置正确的活体检测相似度(1-100)');
			return 0;
		}
		if (intervalMS < 1000) {
			Message.info('请设置活体检测间隔最少1000');
			return 0;
		}
		return 1;
	}

	/** 替换 input 输入框参数 */
	replaceInputValue(prop, value) {
		let result = value;
		if (typeof result === 'string') {
			result = this.validateCheckNum(prop, result);
			result = this.validForbid(result);
			log.info(`replace ${prop} text:`, result);
		}

		if (prop === 'repeatAnswers' || prop === 'blurAnswers') {
			if (result[0].words) {
				result[0].words = this.validForbid(result[0].words);
			}

			if (result[0].wordsEnd) {
				result[0].wordsEnd = this.validForbid(result[0].wordsEnd);
			}

			if (result[0].wordsTimesMax) {
				result[0].wordsTimesMax = this.validateCheckNum('wordsTimesMax', result[0].wordsTimesMax);
			}
		}
		// console.log(prop, 'replaceInputValue', value);\
		//url 允许输入特殊字符
		if (prop === 'informationRushurlAddress') {
			return value;
		}
		return result;
	}

	/** 替换非 number 类型文字, 不替换复数 */
	validateCheckNum(prop, value) {
		if (this.getNumberTypeProperty(prop)) {
			return value
				.toString()
				.replace(/[`~!@#$%^&*()_+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——+={}|《》？：“”【】、；‘’，。、A-Za-z\u4E00-\u9FA5]/g, '')
				.replace(/\s/g, '');
		}
		return value;
	}

	/** 特殊符号替换 */
	validForbid(value) {
		return value.replace(/[`~@$^&()=<>|\\[\]·~@￥%……&（）——=|《》【】]/g, '').replace(/\s/g, '');
	}

	/** 获取 number 类型AI 属性 */
	getNumberTypeProperty(prop) {
		return AITalk.numberInputProperty.indexOf(prop) !== -1;
	}

	/** 节点判断 */
	hasAiSpeak(nodeId) {
		if (!nodeId) {
			log.error('hasAiSpeak error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasAiSpeak.indexOf(id) !== -1;
	}
	hasConfidence(nodeId) {
		if (!nodeId) {
			log.error('hasConfidence error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasConfidence.indexOf(id) !== -1;
	}
	hasEndTemplate(nodeId) {
		if (!nodeId) {
			log.error('hasEndTemplate error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasEndTemplate.indexOf(id) !== -1;
	}
	hasWaitTime(nodeId) {
		if (!nodeId) {
			log.error('hasWaitTime error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWaitTime.indexOf(id) !== -1;
	}
	hasWordsYes(nodeId) {
		if (!nodeId) {
			log.error('hasWordsYes error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsYes.indexOf(id) !== -1;
	}
	hasNextStep(nodeId) {
		if (!nodeId) {
			log.error('hasNextStep error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasNextStep.indexOf(id) !== -1;
	}
	hasNextStepNo(nodeId) {
		if (!nodeId) {
			log.error('hasNextStepNo error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasNextStepNo.indexOf(id) !== -1;
	}
	hasWordsOther(nodeId) {
		if (!nodeId) {
			log.error('hasWordsOther error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsOther.indexOf(id) !== -1;
	}
	hasWordsNoAnswer(nodeId) {
		if (!nodeId) {
			log.error('hasWordsNoAnswer error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsNoAnswer.indexOf(id) !== -1;
	}

	hasRecognizeFailed(nodeId) {
		if (!nodeId) {
			log.error('hasRecognizeFailed error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasRecognizeFailed.indexOf(id) !== -1;
	}
	hasResultFailed(nodeId) {
		if (!nodeId) {
			log.error('hasResultFailed error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasResultFailed.indexOf(id) !== -1;
	}
	hasAiProcessSpeech(nodeId) {
		if (!nodeId) {
			log.error('hasAiProcessSpeech error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasAiProcessSpeech.indexOf(id) !== -1;
	}
	hasAiSpeakTextArea(nodeId) {
		if (!nodeId) {
			log.error('hasAiSpeakTextArea error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasAiSpeakTextArea.indexOf(id) !== -1;
	}
	hasWordsIntention(nodeId) {
		if (!nodeId) {
			log.error('hasWordsIntention error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsIntention.indexOf(id) !== -1;
	}
	hasWordsVariableJudge(nodeId) {
		if (!nodeId) {
			log.error('hasWordsVariableJudge error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsVariableJudge.indexOf(id) !== -1;
	}
	hasWordsInterfaceSelect(nodeId) {
		if (!nodeId) {
			log.error('hasWordsInterfaceSelect error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsInterfaceSelect.indexOf(id) !== -1;
	}
	hasWordsVariable(nodeId) {
		if (!nodeId) {
			log.error('hasWordsVariable error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsVariable.indexOf(id) !== -1;
	}

	hasBusinessInstruct(nodeId) {
		if (!nodeId) {
			log.error('hasBusinessInstruct error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasBusinessInstruct.indexOf(id) !== -1;
	}

	getAnswerTitleLabel(nodeId) {
		const id = this.getTalkId(nodeId);
		return AITalk.templateFormLabel[id];
	}
	getSettingVisiable(nodeId) {
		const id = this.getTalkId(nodeId);
		return id === AITalk.TalkEnum.MESSAGE_SURE;
	}
	hasOtherWaitTime(nodeId) {
		if (!nodeId) {
			log.error('hasOtherWaitTime error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasOtherWaitTime.indexOf(id) !== -1;
	}
	hasNoAnswerOverTime(nodeId) {
		if (!nodeId) {
			log.error('hasNoAnswerOverTime error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasNoAnswerOverTime.indexOf(id) !== -1;
	}

	hasCollectionResultSelect(nodeId) {
		if (!nodeId) {
			log.error('hasCollectionResultSelect error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasCollectionResultSelect.indexOf(id) !== -1;
	}

	hasMultipleSelect(nodeId) {
		if (!nodeId) {
			log.error('hasMultipleSelect error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasMultipleSelect.indexOf(id) !== -1;
	}

	hasWordsOptionJudge(nodeId) {
		if (!nodeId) {
			log.error('hasWordsOptionJudge error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsOptionJudge.indexOf(id) !== -1;
	}
	hasWordsSendContents(nodeId) {
		if (!nodeId) {
			log.error('hasWordsSendContents error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasWordsSendContents.indexOf(id) !== -1;
	}
	hasNlpBranch(nodeId) {
		if (!nodeId) {
			log.error('hasNlpBranch error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasNlpBranch.indexOf(id) !== -1;
	}
	hasSelectVideoIcon(nodeId) {
		if (!nodeId) {
			log.error('hasSelectVideoIcon error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasSelectVideoIcon.indexOf(id) !== -1;
	}

	hasBlurWords(nodeId) {
		if (!nodeId) {
			log.error('hasBlurWords error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasBlurWords.indexOf(id) !== -1;
	}

	hasRepeatWords(nodeId) {
		if (!nodeId) {
			log.error('hasRepeatWords error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasRepeatWords.indexOf(id) !== -1;
	}
	hasRequestApi(nodeId) {
		if (!nodeId) {
			log.error('hasRequestApi error:', 'nodeId is null');
			return;
		}
		const id = this.getTalkId(nodeId);
		return AITalk.hasRequestApi.indexOf(id) !== -1;
	}

	setIvvrOptionsVideo(video) {
		this.ivvrOptionsVideo = [this.ivvrOptionsVideo, video];
	}

	/**
	 * 设置节点属性
	 * @param { String } taskId 节点Id
	 * @param { Object } form 表单数据
	 * @param { Object } workstep cached的ai工作流
	 */
	setTemplateTalkProperty(taskId, form, workstep) {
		let nodeType = '';
		const { audioType, videoType } = this.getRobotProperty();
		if (this.getTalkId(taskId) === 'sendMessage') {
			nodeType = 'screenSnapshot';
		} else {
			nodeType = this.getTalkId(taskId);
		}
		initModalDataWithType(nodeType, form, workstep, videoType === 'pre-recorded-video' && audioType === 'tts');
	}

	/**
	 * 筛选节点属性
	 * @param { String } taskId 节点Id
	 * @param { Object } form 表单数据
	 */
	filterTemplateTalkProperty(taskId, form) {
		let workstep = {};
		const { audioType, videoType } = this.getRobotProperty();
		if (this.getTalkId(taskId) === 'sendMessage') {
			workstep = this.getTemplateNode('screenSnapshot');
		} else if (this.getTalkId(taskId) === 'sendContents') {
			workstep = this.getTemplateNode(form.wordsSendContents.type);
		} else {
			workstep = this.getTemplateNode(taskId);
		}
		let clone = _.cloneDeep(workstep);

		const nodeType = this.getTalkId(taskId);
		clone.id = taskId;
		clone.no = taskId;

		parseModalDataWithType(nodeType, form, clone, videoType === 'pre-recorded-video' && audioType === 'tts');

		if (this.startNode === taskId) {
			clone.hasStartNode = true;
		} else {
			let parentNode = getAllParentNodes(this.talks, taskId);
			clone.hasStartNode = parentNode.includes(this.startNode);
		}
		console.log('####clone', clone, taskId, AITalk);
		return clone;
	}

	pushTemplateAnswer(taskId, step) {
		if (!step) {
			return;
		}
		let workstep = _.cloneDeep(step);
		console.log(taskId, workstep);
		if (this.getTalkId(taskId) === 'messageSure') {
			if (workstep.repeatErrorRemind && (!workstep.repeatErrorRemind.do?.id || !workstep.repeatErrorRemind.after?.id)) {
				if (workstep.answer && !workstep.answer.find(item => item.type === 'repeat')) {
					let repeat = {
						do: {
							data: '',
							command: 'speak',
							variables: [],
							variableId: ''
						},
						key: ['repeat'],
						enableNluLibrary: true,
						amendRules: [],
						type: 'repeat',
						after: {
							command: 'listen'
						}
					};
					workstep.answer.splice(3, 0, repeat);
				}
				// console.log(workstep.answer, 'workstep.answer:');
			}
			if (workstep.fuzzyErrorRemind && (!workstep.fuzzyErrorRemind.do?.id || !workstep.fuzzyErrorRemind.after?.id)) {
				if (workstep.answer && !workstep.answer.find(item => item.type === 'fuzzy')) {
					let fuzzy = {
						do: {
							data: '',
							command: 'speak',
							variables: [],
							variableId: ''
						},
						key: ['fuzzy'],
						enableNluLibrary: true,
						amendRules: [],
						type: 'fuzzy',
						after: {
							command: 'listen'
						}
					};
					workstep.answer.splice(4, 0, fuzzy);
					// console.warn(workstep.answer, 'workstep.answer:');
				}
			}
		}
		console.warn('pushTemplateAnswer:', workstep.answer);
		return workstep;
	}

	// 获取默卡证采集选项
	getDefaultCardCollectionOptions() {
		return AITalk.defaultCardCollectionOptions;
	}
}

const AIWorkflow = new WorkFlow();

export default AIWorkflow;
